<template>
  <el-container class="main-container">
    <el-container>
      <el-container>
        <el-main>
          <div class="user-info">
            <el-row class="toolbar">
              <el-col :span="12" class="search-area">
                <el-input v-model="searchForm.userId" placeholder="ID" clearable class="search-input"></el-input>
                <el-input v-model="searchForm.username" placeholder="Name" clearable class="search-input"></el-input> <!-- 新添加的用户名搜索 -->
                <el-button type="primary" icon="el-icon-search" @click="searchUsers">Search</el-button> <!-- 修改调用方法 -->
                <el-button type="default" @click="fetchAllUsers">Fetch All Users</el-button>
                <el-button type="default" @click="navigateTo('PaymentInfo')">Go to Payment Info</el-button>
              </el-col>
              <el-col :span="12" class="action-area">
                <el-button type="success" icon="el-icon-plus" @click="openAddDialog">Add User</el-button>
              </el-col>
            </el-row>

            <!-- User Info Table -->
            <el-table :data="currentUsers" stripe border :row-class-name="tableRowClassName">
              <el-table-column label="No." width="60" type="index" :index="calculateIndex" />
              <el-table-column prop="userId" label="User ID" width="100" />
              <el-table-column prop="username" label="Username" />
              <el-table-column prop="contactInfo" label="Contact Info" />
              <el-table-column label="Actions" width="180">
                <template slot-scope="scope">
                  <el-button size="small" type="text" @click="openEditDialog(scope.row)">Edit</el-button>
                  <el-button size="small" type="text" @click="deleteUser(scope.row.userId)">Delete</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- Pagination -->
            <el-pagination
                :current-page="currentPage"
                :page-size="pageSize"
                :total="totalUsers"
                @current-change="handlePageChange">
            </el-pagination>

            <!-- Add/Edit Dialog -->
            <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
              <el-form :model="userForm" label-width="120px">
                <el-form-item label="User ID">
                  <el-input v-model="userForm.userId" disabled></el-input> <!-- Keep User ID disabled during edit -->
                </el-form-item>
                <el-form-item label="Username">
                  <el-input v-model="userForm.username"></el-input>
                </el-form-item>
                <el-form-item label="Password">
                  <el-input v-model="userForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="Contact Info">
                  <el-input v-model="userForm.contactInfo"></el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">Cancel</el-button>
                <el-button type="primary" @click="saveUser">Save</el-button>
              </div>
            </el-dialog>

          </div>

        </el-main>
      </el-container>
    </el-container>
  </el-container>
</template>

<script>
import { getUserById, getAllUsers, addUser, updateUser, deleteUser } from '@/api/userInfo';

export default {
  name: 'UserInfo',
  data() {
    return {
      users: [],
      currentUsers: [],
      totalUsers: 0, // 总用户数
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示的用户数量
      searchForm: {
        userId: '',
        username: '' // 新增用于用户名的搜索
      },
      userForm: {
        userId: null,
        username: '',
        password: '',
        contactInfo: ''
      },
      dialogVisible: false,
      dialogTitle: '',
    };
  },
  computed: {
    filteredUsers() {
      if (!Array.isArray(this.users)) {
        return [];
      }
      return this.users;
    }
  },
  methods: {
    navigateTo(routeName) {
      this.$router.push({ name: routeName }).catch(err => {
        if (err.name != 'NavigationDuplicated') {
          throw err;
        }
      });
    },
    fetchAllUsers() {
      getAllUsers().then(response => {
        this.users = response; // 获取所有用户
        this.totalUsers = response.length; // 更新总用户数
        this.updateCurrentUsers(); // 更新当前用户数据
      });
    },
    updateCurrentUsers() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.currentUsers = this.users.slice(start, end); // 根据索引获取当前用户数据
    },
    handlePageChange(page) {
      this.currentPage = page; // 更新当前页码
      this.updateCurrentUsers(); // 更新当前显示的用户
    },
    searchUsers() {
      const userId = this.searchForm.userId;
      const username = this.searchForm.username;

      // 根据 userId 和 username 执行搜索逻辑
      if (userId) {
        getUserById(userId).then(response => {
          this.currentUsers = response ? [response] : []; // 更新当前用户信息
        }).catch(error => {
          console.error('Error fetching user by ID:', error);
        });
      } else if (username) {
        // 可扩展：为用户名实现相应的 API 调用
        this.currentUsers = this.users.filter(user => user.username.includes(username)); // 简单的客户端过滤
      } else {
        this.fetchAllUsers(); // 如果都为空，则获取所有用户
      }
    },
    openAddDialog() {
      this.dialogTitle = 'Add User';
      this.userForm = { userId: null, username: '', password: '', contactInfo: '' };
      this.dialogVisible = true;
    },
    openEditDialog(user) {
      this.dialogTitle = 'Edit User';
      this.userForm = { ...user }; // 填充当前用户数据
      this.dialogVisible = true;
    },
    saveUser() {
      const apiCall = this.userForm.userId ? updateUser(this.userForm) : addUser(this.userForm);
      apiCall.then(() => {
        this.fetchAllUsers(); // 刷新用户列表
        this.dialogVisible = false; // 关闭对话框
      }).catch(error => {
        console.error('Error saving user:', error); // 捕获错误
      });
    },
    deleteUser(userId) {
      this.$confirm('Are you sure to delete this user?', 'Warning', {
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        type: 'warning'
      }).then(() => {
        deleteUser(userId).then(() => {
          this.fetchAllUsers(); // 刷新用户列表
        });
      }).catch(err => {
        console.error('Error deleting user:', err);
      });
    },
    calculateIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    tableRowClassName(row, index) {
      return index % 2 ? 'even-row' : 'odd-row';
    }
  },
  mounted() {
    this.fetchAllUsers(); // 组件挂载时获取所有用户信息
  }
};
</script>

<style>
.user-info {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.action-area .el-button {
  margin-left: 10px;
}
</style>
